package com.esperia09.webservice.mixiVoiceNotify;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.esperia09.webservice.mixiVoiceNotify.common.SendRequest;

public class MyVoiceList extends HttpServlet {
	private static final String OAUTH_AFTER_REDIRECT_URL = "http%3A%2F%2Fmixi-voice-notify.appspot.com%2Fcallback.jsp"; // local

	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		req.setCharacterEncoding("UTF-8");
		resp.setContentType("application/json");
		
		String myTimelineRequestStr = "http://api.mixi-platform.com/2/voice/statuses/@me/user_timeline"
			+ "?oauth_token=" + req.getParameter("code");
		String data = getMyVoiceList(myTimelineRequestStr, req.getParameter("code"));
		System.out.println(data);
		resp.getWriter().println(data);
	}
	
	/**
	 * mixiにAccessToken/RefreshTokenをリクエストする
	 * @param authCode
	 * @return
	 * @throws IOException
	 */
	public static String getMyVoiceList(String accessUrl, String accessToken) throws IOException {
		if(accessToken == null) {
			return "{}";
		}
		
		HttpURLConnection con = null;
		String result = "{}";
		try {
		    URL url = new URL(accessUrl);
		    con = (HttpURLConnection) url.openConnection();
		    // con.setRequestProperty("Authorization", "OAuth " + accessToken);
		    
		    result = SendRequest.sendGet(con);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
		    if (con != null) con.disconnect();
		}
		
		return result;
	}
}
